package com.huaxinkai.mobile.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * socket客户端
 * @author liuzh
 * @date 2017年1月14日下午10:38:15
 */
public class SocketClient {

	public static void main(String[] args) {
		try {
			//创建一个socket，指定服务器和端口
			Socket socket = new Socket("localhost",8888);
			//获取输流，发送消息
			OutputStream os = socket.getOutputStream();//字节输出流
			PrintWriter pw = new PrintWriter(os);//将输出流打包成打印流
			pw.write("用户：admin;密码：123");
			pw.flush();
			socket.shutdownOutput();//关闭输出流
			
			//获取输入流  接收响应
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String info = null;
			while( (info = br.readLine()) != null){
				System.out.println("我是客户端,服务器说：" + info);
			}
			
			br.close();
			isr.close();
			is.close();
			
			//关闭其他资源
			pw.close();
			os.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
